package bitetorrentserver;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author user
 */
public class Files {

    public ArrayList<File> files;
    public String filename = "files.tra";

    public Files(String filename) {
        try {
            this.open();
        } catch (IOException ex) {
            files = new ArrayList<File>();
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Files.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void open() throws IOException, ClassNotFoundException {
        // baca files secara serialisasi
        FileInputStream fis = new FileInputStream(filename);
        ObjectInputStream in = new ObjectInputStream(fis);
        files = (ArrayList<File>) in.readObject();
        in.close();
    }

    public void save() throws IOException {
        // simpan files dalam bentuk serialisasi
        FileOutputStream fos = new FileOutputStream(filename);
        ObjectOutputStream out = new ObjectOutputStream(fos);
        out.writeObject(files);
        out.close();
    }

    public void add(File file) {
        for (int i = 0; i < files.size(); ++i) {
            if (files.get(i).compareTo(file) == 0) {
                // File no unique
                return;
            }
        }
        // File is unique
        files.add(file);
    }

    @Override
    public String toString() {
        String s = "";

        for (int i = 0; i < files.size(); ++i) {
            s += files.get(i).toString() + "\n";
        }

        return s;
    }
}
